<template>
	<view class="content">
		<uni-section title="车辆信息" type="line">
			<uni-list>
				<uni-list-item title="司机姓名" :rightText="(valiFormData.driverinfo && valiFormData.driverinfo.name) || ''"
					:showArrow="false"></uni-list-item>
				<uni-list-item title="车型" :rightText="(valiFormData.driverinfo && valiFormData.driverinfo.model) || ''"
					:showArrow="false"></uni-list-item>
				<uni-list-item title="车牌号"
					:rightText="(valiFormData.driverinfo && valiFormData.driverinfo.license) || ''"
					:showArrow="false"></uni-list-item>
			</uni-list>
		</uni-section>

		<uni-section title="加油信息" type="line">
			<uni-forms ref="form" :rules="rules" :model="valiFormData" validate-trigger="bind">
				<!-- 加油量 -->
				<uni-forms-item label="加油量" required name="fuelAmount">
					<uni-easyinput type="digit" v-model="valiFormData.fuelAmount" placeholder="请输入加油量" />
					<uni-file-picker :value="fuelAmountImages" @select="onFuelAmountSelect" @delete="onFuelAmountDelete"
						:auto-upload="false" limit="1" title="上传加油量照片" fileMediatype="image" />
				</uni-forms-item>

				<!-- 汽油类型 -->
				<uni-forms-item label="汽油类型" required name="fuelType">
					<uni-data-select v-model="valiFormData.fuelType" :localdata="fuelTypes" @change="change" />
				</uni-forms-item>

				<!-- 当前油价 -->
				<uni-forms-item label="当前油价" required name="currentPrice">
					<uni-easyinput type="digit" v-model="valiFormData.currentPrice" placeholder="请输入当前油价" />
				</uni-forms-item>

				<!-- 当前里程数 -->
				<uni-forms-item label="当前里程数" required name="currentMileage">
					<uni-easyinput type="digit" v-model="valiFormData.currentMileage" placeholder="请输入当前里程数" />
					<uni-file-picker :value="mileageImages" @select="onMileageSelect" @delete="onMileageDelete"
						:auto-upload="false" limit="1" title="上传里程表照片" fileMediatype="image" />
				</uni-forms-item>

				<!-- 计算费用 -->
				<uni-forms-item label="加油费用" required>
					<uni-easyinput :value="calculatedCost" disabled />
				</uni-forms-item>
			</uni-forms>

			<button class="button" type="primary" @click="submitForm">提交</button>
		</uni-section>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				_id: null,
				value: null,
				valiFormData: {
					driverinfo: [],
					fuelAmount: null,
					fuelType: null,
					currentPrice: null,
					currentMileage: null,
					fuelthumb: '',
					milethumb: '',
					create_date: '',
					cost: null,
					edit_date: ''
				},
				fuelTypes: [{
						value: 0,
						text: "92#汽油"
					},
					{
						value: 1,
						text: "95#汽油"
					},

				],
				fuelAmountImages: [],
				mileageImages: [],
				rules: {
					fuelAmount: {
						rules: [{
								required: true,
								errorMessage: '加油量不能为空'
							},
							{
								format: 'number',
								errorMessage: '只能输入数字'
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if (value <= 0) {
										callback('加油量必须大于0')
									}
									return true
								}
							},
							// {
							// 	pattern: '^\d+(\.\d{1,1})?$',
							// 	errorMessage: '最多保留一位小数'
							// }
						]
					},
					fuelType: {
						rules: [{
							required: true,
							errorMessage: '请选择汽油类型'
						}]
					},
					currentPrice: {
						rules: [{
								required: true,
								errorMessage: '油价不能为空'
							},
							{
								format: 'number',
								errorMessage: '只能输入数字'
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if (value <= 0) {
										callback('油价必须大于0')
									}
									return true
								}
							},
							// {
							// 	pattern: '^\d+(\.\d{1,2})?$',
							// 	errorMessage: '最多保留两位小数'
							// }
						]
					},
					currentMileage: {
						rules: [{
								required: true,
								errorMessage: '里程数不能为空'
							},
							{
								format: 'number',
								errorMessage: '只能输入数字'
							},
							{
								validateFunction: (rule, value, data, callback) => {
									if (value < 0) {
										callback('里程数不能为负数')
									}
									return true
								}
							},
							// {
							// 	pattern: '^\d+(\.\d{1,1})?$',
							// 	errorMessage: '最多保留一位小数'
							// }
						]
					}
				}
			}
		},
		computed: {
			calculatedCost() {
				if (this.valiFormData.fuelAmount && this.valiFormData.currentPrice) {
					this.valiFormData.cost = (this.valiFormData.fuelAmount * this.valiFormData.currentPrice).toFixed(2)
				}
				return this.valiFormData.cost
			}
		},
		mounted() {
			this._id = uni.$router.params._id
			this.initData(this._id)
		},

		methods: {
			// 初始化数据（添加 isCloud 标记）
			async initData(_id) {
				const obj = uniCloud.importObject('driver')
				const res = await obj.getFuelRecordById({
					_id
				}).then(r => {
					if (r.code === 0) {
						this.valiFormData = r.data[0]
						if (r.data[0].fuelthumb) {
							this.fuelAmountImages = [{
								url: r.data[0].fuelthumb,
								isCloud: true // 标记为云端文件
							}]
						}
						if (r.data[0].milethumb) {
							this.mileageImages = [{
								url: r.data[0].milethumb,
								isCloud: true // 标记为云端文件
							}]
						}
					}
				})
			},
			// 选择汽油种类
			change(e) {
				// //console.log(e, 'change')
				this.valiFormData.fuelType = e.value ?? null
				// this.value = e?._id || null
			},
			// 文件选择事件
			onFuelAmountSelect(e) {
				this.fuelAmountImages = e.tempFiles.map(file => ({
					...file,
					isCloud: false // 标记为本地文件
				}))
			},
			onMileageSelect(e) {
				this.mileageImages = e.tempFiles.map(file => ({
					...file,
					isCloud: false // 标记为本地文件
				}))
			},

			// 文件删除事件
			onFuelAmountDelete() {
				this.fuelAmountImages = []
			},
			onMileageDelete() {
				this.mileageImages = []
			},

			// 生成云存储路径（与 add.vue 一致）
			generateCloudPath(originalName) {
				const ext = originalName.split('.').pop()
				const timestamp = Date.now()
				const date = uni.$dayjs(timestamp).format('YYYY-MM-DD')
				const mobile = uni.getStorageSync('userInfo').mobile
				return `fuel/${mobile}/${date}/${timestamp}.${ext}`
			},

			// 上传单个文件
			async uploadFile(file) {
				const cloudPath = this.generateCloudPath(file.name)
				return uniCloud.uploadFile({
					filePath: file.path || file.url,
					cloudPath,
					cloudPathAsRealPath: true
				})
			},

			// 提交表单（包含文件上传逻辑）
			async submitForm() {
				try {
					// 1. 表单验证
					const valid = await this.$refs.form.validate()
					if (!valid) return

					// 图片校验
					if (this.fuelAmountImages.length === 0) {
						return uni.showToast({
							title: '请上传加油量照片',
							icon: 'none'
						})
					}
					if (this.mileageImages.length === 0) {
						return uni.showToast({
							title: '请上传里程表照片',
							icon: 'none'
						})
					}

					// 2. 处理加油量图片
					if (this.fuelAmountImages.length > 0) {
						const file = this.fuelAmountImages[0]
						if (!file.isCloud) {
							const res = await this.uploadFile(file)
							this.valiFormData.fuelthumb = res.fileID
						}
					} else {
						this.valiFormData.fuelthumb = ''
					}

					// 3. 处理里程数图片
					if (this.mileageImages.length > 0) {
						const file = this.mileageImages[0]
						if (!file.isCloud) {
							const res = await this.uploadFile(file)
							this.valiFormData.milethumb = res.fileID
						}
					} else {
						this.valiFormData.milethumb = ''
					}

					// 4. 提交数据
					this.valiFormData.edit_date = uni.$dayjs().format('YYYY-MM-DD HH:mm:ss')
					const {
						_id,
						...data
					} = this.valiFormData

					const obj = uniCloud.importObject('driver')
					await obj.updateFuelRecord({
						_id: this._id,
						data
					})

					uni.showToast({
						title: '提交成功'
					})
					setTimeout(() => uni.navigateBack(), 1000)

				} catch (err) {
					console.error('提交失败', err)
					uni.showToast({
						title: `提交失败: ${err.message}`,
						icon: 'none'
					})
				}
			},
			// 重置表单
			resetForm() {
				// 重置数据
				this.valiFormData = {
					fuelAmount: null,
					fuelType: null,
					currentPrice: null,
					currentMileage: null,
					fulethumb: '',
					milethumb: '',
					create_date: ''
				}

				// 重置组件状态
				this.value = null
				this.fuelAmountImages = [] // 必须保持数组类型
				this.mileageImages = []
				// this.$refs.valiForm.clearValidate()
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: linear-gradient(145deg, #f0f8ff, #e6f7ff);
		height: 100%;
		font-family: 'PingFang SC', 'Helvetica Neue', 'Microsoft YaHei', sans-serif;
	}

	.content {
		padding: 20rpx;
		background: rgba(255, 255, 255, 0.92);
		border-radius: 20rpx;
		margin: 20rpx;
		box-shadow: 0 8rpx 30rpx rgba(0, 82, 217, 0.1);
		position: relative;
		overflow: hidden;
	}

	.content::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 10rpx;
		background: linear-gradient(90deg, #1e88e5, #42a5f5, #64b5f6);
		z-index: 1;
	}

	/* 标题样式 */
	::v-deep .uni-section__title {
		color: #1976d2;
		font-weight: bold;
		font-size: 34rpx;
		border-left: 8rpx solid #42a5f5;
		padding-left: 20rpx;
		text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);
	}

	/* 表单整体样式 */
	::v-deep .uni-forms {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 16rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 20rpx rgba(33, 150, 243, 0.1);
	}

	/* 表单标签样式 */
	::v-deep .uni-forms-item__label {
		width: 200rpx !important;
		min-width: 200rpx !important;
		flex-shrink: 0;
		padding-right: 20rpx;
		font-size: 28rpx;
		line-height: 1.6;
		white-space: normal;
		color: #1976d2;
		font-weight: 500;
	}

	/* 输入框样式 */
	::v-deep .uni-easyinput__content {
		border: 1px solid #bbdefb;
		border-radius: 12rpx;
		background: #f8fbff;
		transition: all 0.3s;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
	}

	::v-deep .uni-easyinput__content:focus-within {
		border-color: #42a5f5;
		box-shadow: 0 0 10rpx rgba(33, 150, 243, 0.3);
	}

	::v-deep .uni-input-input {
		color: #1565c0;
		font-size: 28rpx;
	}

	/* 选择器样式 */
	::v-deep .uni-data-select {
		border: 1px solid #bbdefb;
		border-radius: 12rpx;
		background: #f8fbff;
		transition: all 0.3s;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
	}

	::v-deep .uni-data-select:hover,
	::v-deep .uni-data-select:focus {
		border-color: #42a5f5;
		box-shadow: 0 0 10rpx rgba(33, 150, 243, 0.3);
	}

	/* 文件上传样式 */
	::v-deep .uni-file-picker {
		margin-top: 20rpx;
	}

	::v-deep .uni-file-picker__header {
		color: #1976d2;
		font-weight: 500;
	}

	::v-deep .uni-file-picker__box {
		border: 1px dashed #90caf9;
		border-radius: 12rpx;
		background: #f1f8ff;
		transition: all 0.3s;
	}

	::v-deep .uni-file-picker__box:hover {
		border-color: #42a5f5;
		background: #e3f2fd;
	}

	/* 列表样式 */
	::v-deep .uni-list {
		background: #f8fbff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
	}

	::v-deep .uni-list-item {
		border-bottom: 1px solid #e3f2fd;
	}

	::v-deep .uni-list-item__content-title {
		color: #1976d2;
		font-weight: 500;
	}

	::v-deep .uni-list-item__extra-text {
		color: #0d47a1;
		font-weight: bold;
	}

	/* 按钮样式 */
	.button {
		width: 100%;
		height: 90rpx;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: bold;
		background: linear-gradient(135deg, #1976d2, #42a5f5);
		color: white;
		border: none;
		box-shadow: 0 6rpx 16rpx rgba(25, 118, 210, 0.3);
		transition: all 0.3s;
		margin-top: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.button:active {
		transform: translateY(4rpx);
		box-shadow: 0 2rpx 8rpx rgba(25, 118, 210, 0.4);
	}

	/* 禁用输入框样式 */
	::v-deep .uni-easyinput__content.is-disabled {
		background-color: #e3f2fd;
		color: #0d47a1;
	}

	/* 日期选择器样式 */
	::v-deep .uni-date-editor--x {
		border: 1px solid #bbdefb;
		border-radius: 12rpx;
		background: #f8fbff;
		transition: all 0.3s;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.03);
	}

	::v-deep .uni-date-editor--x:hover,
	::v-deep .uni-date-editor--x:focus {
		border-color: #42a5f5;
		box-shadow: 0 0 10rpx rgba(33, 150, 243, 0.3);
	}

	/* 科技感装饰 */
	.tech-decoration {
		position: absolute;
		top: 0;
		right: 0;
		width: 150rpx;
		height: 150rpx;
		background: linear-gradient(135deg, transparent 50%, rgba(33, 150, 243, 0.1) 50%);
		border-bottom-left-radius: 100%;
		z-index: 0;
	}

	/* 表单项间距 */
	::v-deep .uni-forms-item {
		margin-bottom: 30rpx;
	}
</style>